package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;
	@Override
	public boolean login(String username, String password) {
		log.debug("service_provide...u:"+username+" p:"+password);
		if("admin".equals(username) && "123".equals(password)){
			return true;
		}else{
			throw new BusinessRuntimeException("登录失败");
		}
	}

	@Override
	public SysUser findByUsername(String username) {
		return userDao.findByUsername(username);
	}

    @Override
    public void add(SysUser sysUser, Integer[] roleIds) {
		//添加用户基本信息
		userDao.addUser(sysUser);
        //维护用户与角色之间的关系
		setRelation(sysUser.getId(),roleIds);
    }

	@Override
	public PageResult findPage(QueryPageBean queryPageBean) {
		//开始分页,传入参数为页码,每页最大条数
		PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
		//查询所有的用户数据
		Page<Map<String,Object>> page = userDao.findByCondition(queryPageBean.getQueryString());
		/*//如果返回数据不为空,将日期格式转换为字符串传给页面
		if (page!=null){
			for (int i = 0; i <page.size() ; i++) {
				Map<String,Object> map = page.get(i);
				if (map.get("birthday")!=null){
                    Date date = (Date) map.get("birthday");
					String birthdayStr = DateUtils.parseDate2String(date);
					map.put("birthday",birthdayStr);
				}
				page.add(map);
			}
		}*/
		return new PageResult(page.getTotal(),page);
	}

    @Override
    public Map<String, Object> findUserById(Integer id) {
        return userDao.findUserById(id);
    }

    @Override
    public List<Integer> findroleIdsByUserId(Integer userId) {
        return userDao.findroleIdsByUserId(userId);
    }

    @Override
    public void edit(SysUser sysUser, Integer[] roleIds) {
	    //删除所有关系,通过用户id删除角色id
        userDao.delRelation(sysUser.getId());
        //编辑用户基本信息
        userDao.edit(sysUser);
        //建立新的关系
        setRelation(sysUser.getId(),roleIds);
    }

    @Override
    public void delUserById(Integer id) {
        //删除用户与角色的关联关系
        userDao.delRelation(id);
        //删除用户信息
        userDao.delUserById(id);
    }

    private void setRelation(Integer userId, Integer[] roleIds) {
		//进行判断选择的角色id不为空
		if (userId!=null && roleIds!=null && roleIds.length>0){
			for (Integer roleId : roleIds) {
				userDao.setRelation(userId,roleId);
			}
		}
	}
}